package sample4.provider;

import sample4.provider.MyDatabase.MyTable;
import sample4.provider.MyDatabase.MyView;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;

/**
 * @author YUN
 */
public class MyContentProvider extends ContentProvider {

    private static final int MYTABLE_DIR = 1;
    private static final int MEYTABLE_ITEM = 2;
    private static final int MYVIEW_DIR = 3;
    private static final int MEVIEW_ITEM = 4;

    private static final UriMatcher sUriMatcher;
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(MyDatabase.AUTHORITY, MyTable.NAME, MYTABLE_DIR);
        sUriMatcher.addURI(MyDatabase.AUTHORITY, MyTable.NAME + "/#", MEYTABLE_ITEM);
        sUriMatcher.addURI(MyDatabase.AUTHORITY, MyView.NAME, MYVIEW_DIR);
        sUriMatcher.addURI(MyDatabase.AUTHORITY, MyView.NAME + "/#", MEVIEW_ITEM);
    }

    private MySQLiteOpenHelper mSQLite;

    //
    @Override
    public boolean onCreate() {
        mSQLite = new MySQLiteOpenHelper(getContext());
        return true;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case MEYTABLE_ITEM:
            return MyTable.ITEM_TYPE;
        case MYTABLE_DIR:
            return MyTable.DIR_TYPE;
        case MEVIEW_ITEM:
            return MyView.ITEM_TYPE;
        case MYVIEW_DIR:
            return MyView.DIR_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }
    @Override
    public int bulkInsert(Uri uri, ContentValues[] initialValues) {
        //
        if (initialValues == null) {
            throw new IllegalArgumentException("initialValues is null.");
        }

        int count = 0;
        SQLiteDatabase db = mSQLite.getWritableDatabase();
        db.beginTransaction();
        try {
            switch (sUriMatcher.match(uri)) {
            case MYTABLE_DIR:
                for (ContentValues value : initialValues) {
                    long id = db.insert(MyTable.NAME, MyTable.Columns.NAME, value);
                    if (0 < id) {
                        count++;
                    }
                }
                db.setTransactionSuccessful();
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
            }
        } finally {
            db.endTransaction();
        }

        if (0 < count) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        //
        if (initialValues == null) {
            throw new IllegalArgumentException("initialValues is null.");
        }

        long id;
        SQLiteDatabase db = mSQLite.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
        case MYTABLE_DIR:
            id = db.insert(MyTable.NAME, null, initialValues);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        Uri insertedUri = null;
        if (0 < id) {
            insertedUri = ContentUris.withAppendedId(uri, id);
            getContext().getContentResolver().notifyChange(insertedUri, null);
        }

        return insertedUri;
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        int count = 0;
        SQLiteDatabase db = mSQLite.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
        case MEYTABLE_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYTABLE_DIR:
            count = db.update(MyTable.NAME, values, where, whereArgs);
            break;
        // ------
        case MEVIEW_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYVIEW_DIR:
            count = db.update(MyView.NAME, values, where, whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (0 < count) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return count;
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        int count = 0;
        SQLiteDatabase db = mSQLite.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
        case MEYTABLE_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYTABLE_DIR:
            count = db.delete(MyTable.NAME, where, whereArgs);
            break;
        // ------
        case MEVIEW_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYVIEW_DIR:
            count = db.delete(MyTable.NAME, where, whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (0 < count) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return count;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
        String sql = null;

        switch (sUriMatcher.match(uri)) {
        case MEYTABLE_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYTABLE_DIR:
            sql = SQLiteQueryBuilder.buildQueryString(false, MyTable.NAME, projection, where, null, null, sortOrder, null);
            break;
        // ------
        case MEVIEW_ITEM:
            where = BaseColumns._ID + "=" + uri.getLastPathSegment() + (where == null ? "" : " AND (" + where + ")");
        case MYVIEW_DIR:
            sql = SQLiteQueryBuilder.buildQueryString(false, MyView.NAME, projection, where, null, null, sortOrder, null);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        Cursor c = mSQLite.getReadableDatabase().rawQuery(sql, whereArgs);
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    }
}
